/**
 * 
 */
package com.cipe.cmrs.converter;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.util.StringUtils;

public class DateEditor extends PropertyEditorSupport {
	private static String inPattern = "MM/dd/yyyy";
	private static String outPattern = "MM/dd/yyyy";
	
	public DateEditor() { }
	
	public DateEditor(String inPattern, String outPattern) { 
		super();
		
		if(inPattern != null) this.inPattern = inPattern;
		if(outPattern != null) this.outPattern = outPattern;
	}
	
	public void setAsText(String source) {
		Date date = null;
		if (StringUtils.hasText(source)) {
			try {
				DateFormat formatter = new SimpleDateFormat(inPattern);

				date = (Date) formatter.parse(source);
			} catch (ParseException ex) {
				throw new java.lang.IllegalArgumentException(ex);
			}
		}
		setValue(date);
	}

    public String getAsText() {
    	Object o = getValue();
    	if(o instanceof Date) {
    		DateFormat formatter = new SimpleDateFormat(outPattern);
    		return formatter.format((Date)o);
    	}
    	return ("" + (o != null ? o : ""));
    }
}
